import SimpleXMLRPCServer
import psycopg2
import sys
import xmlrpclib

class Server:
    def __init__(self): 
	self.con = None
	self.cur = None
    
    def ping(self):
        return True
    
    def now(self):
        return datetime.datetime.now()
    
    def show_type(self, arg):
        return (str(arg), str(type(arg)), arg)

    def add_trans(self, cc_num, amount):
	row_value = "'%s', '%s'" % (cc_num, amount)
        return self._sql_insert('cc_account', row_value)

    def _sql_insert(self, table, row):
        try:
            self._sql_connect()

            query = "INSERT INTO %s VALUES (%s)" % (table, row)
	    print query
            self.cur.execute(query)
            # row standard format (i.e. 2,'Mercedes',57127)
            self.con.commit()
        except Exception as e:
            if self.con:
                self.con.rollback()

            print 'Error %s' % e    
            sys.exit(1)
        
        finally:
            return self._sql_disconnect()

    def _sql_connect(self):
        self.con = psycopg2.connect(database='cps316', user='postgres') 
	self.cur = self.con.cursor()
    
    def _sql_disconnect(self):
        if self.con:
            self.con.close()
        return False

# server running  
server = SimpleXMLRPCServer.SimpleXMLRPCServer(('ec2-50-16-47-119.compute-1.amazonaws.com', 8001), logRequests=True, allow_none=True)
server.register_introspection_functions()
server.register_multicall_functions()
server.register_instance(Server())
try:
    print 'running cc server'
    server.serve_forever()
except KeyboardInterrupt:
    print 'Exiting'

